package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.impl.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/oauth")
@CrossOrigin
public class LoginController
{
    
    @Autowired
    private AuthService authService;
    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @RequestMapping("/toLogin")
    public String tologin(Model model,@RequestParam("FROM")String from)
    {
        model.addAttribute("from",from);
        return "login";
    }


    @PostMapping("/login")
    @ResponseBody
    public Result login(String username,String password){
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new RuntimeException("用户名或密码不存在!");
        }

        AuthToken authToken = authService.authToken(username, password, clientId, clientSecret);
        String jti = authToken.getJti();
        saveJtiCookie(jti);
        return new Result(true, StatusCode.OK,"登录成功");
    }
    private void saveJtiCookie(String jti){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
    }
}
